package com.wanxi.dao.impl;

import com.wanxi.dao.ProductDao;
import com.wanxi.model.ProductModel;
import com.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDaoImpl implements ProductDao {
    @Override
    public List<ProductModel> getProductModelList(ProductModel productModel) {
        String sql = " select * from product where where_show=" + productModel.getWhereShow();
        sql += " order by id desc ";
        sql += " limit " + productModel.getLimit();
        return getList(sql);
    }

    @Override
    public List<ProductModel> findById(ProductModel productModel) {
        String sql = "  select * from product where id=" +
                "  (select max(id) from product where id<" + productModel.getId() +
                "  ) union all" +
                "  select * from product where id=" + productModel.getId() +
                "  union all" +
                "    select * from product where id=" +
                "  (select min(id) from product where id>" + productModel.getId() +
                ")";


        return getList(sql);
    }

    @Override
    public List<ProductModel> findAll(ProductModel productModel) {
        String sql = "select * from product where enable=1 ";
        if (productModel.getCuisineId() != -1) {
            sql += " and cuisine_id=" + productModel.getCuisineId();
        }

        sql += " limit " + (productModel.getPage() - 1) * productModel.getLimit() + "," + productModel.getLimit();
        return getList(sql);
    }

    @Override
    public ProductModel count(ProductModel productModel) {
        String sql = "select count(*) count from product where enable=1 ";
        if (productModel.getCuisineId() != -1) {
            sql += " and cuisine_id=" + productModel.getCuisineId();
        }
        int count = JDBC.count(sql);
        ProductModel model = new ProductModel();
        model.setCount(count);
        return model;
    }

    private List<ProductModel> getList(String sql) {
        List<ProductModel> list = new ArrayList<>();
        ResultSet resultSet = JDBC.query(sql);
        try {
            while (resultSet.next()) {
                ProductModel model = new ProductModel();
                model.setId(resultSet.getInt("id"));
                model.setName(resultSet.getString("name"));
                model.setImgHref(resultSet.getString("img_href"));
                model.setContent(resultSet.getString("content"));
                model.setNormalPrice(resultSet.getBigDecimal("normal_price"));
                model.setMarketPrice(resultSet.getBigDecimal("price"));
                model.setCuisineId(resultSet.getInt("cuisine_id"));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
